import React, { Component } from 'react'
import { connect } from 'react-redux'
// action creator
import { getUsers,deleteUser } from '../store/actions/userAction'

const mapPropsToState = state => {
  return {
    users: state.users
  }
}

const mapPropsToDispatch = dispatch => {
  return {
    getUserList() {
      dispatch(getUsers())
    },
    deleteUser(id,index){
      dispatch(deleteUser(id,index))
    }
  }
}

// 参1 把state映射到props中
// 参2 dispatch方法映射到props中
@connect(mapPropsToState, mapPropsToDispatch)
class Home extends Component {

  componentDidMount() {
    this.props.getUserList()
  }

  render() {
    return (
      <div>
        <ul>
          {
            this.props.users.map((item,index) => {
              return (
                <li key={item._id}>
                  {item.username}
                  <button  onClick={() => this.props.history.push(`/edit/${item._id}`)}>修改</button>
                  <button onClick={()=>this.props.deleteUser(item._id,index)}>删除</button>
                </li>
              )
            })
          }
        </ul>
      </div>
    )
  }
}
export default Home
